package aufgabe3_chat;

import java.io.IOException;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

import aufgabe3_chat.chatGui.ChatFenster;

public class Client_UDP_receive extends Thread{

	Chat_User_Administration chat_user;
	ChatFenster chatfenster;
	DatagramSocket serverSocket;
	Logger logger;
	private final int packetsize;
	
	public Client_UDP_receive(Chat_User_Administration chat_user, ChatFenster chatfenster, DatagramSocket udpSocket, Logger logger, int packetsize){
		
		
		this.packetsize = packetsize;
		setDaemon(true); 
		
		this.chat_user = chat_user;
		this.chatfenster = chatfenster;
		this.logger = logger;
		logger.log("Client_UDP_receive", "DatagramSocket",  "wird an Receive �bergeben");
		serverSocket = udpSocket;
		logger.log("Client_UDP_receive", "Constuctor", "Objekt Erzeugt");
	}
	
	public void run()
    {
		try {		
          while(true){
        	  	byte[] receiveData = new byte[packetsize];
                DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
                serverSocket.receive(receivePacket);	
                String message = new String( receivePacket.getData());
                message = message.trim();
                
                logger.log("Client_UDP_receive", "RECEIVED Message", message);
                message = message + "\n";

                String[] splitInput = message.split(":" , 2);
                
                if(chat_user.has_user(receivePacket.getAddress().getHostName(), splitInput[0])){
                	chatfenster.add_line(message);
                }
             }
          
		} catch (SocketException e1) {
			e1.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
    } 
	
}
